package cc.linker.steplink.crm.merchant.service;

import cc.linker.steplink.crm.commons.BeanMapUtils;
import cc.linker.steplink.crm.commons.form.FormRequest;
import cc.linker.steplink.crm.commons.model.PcUserInfo;
import cc.linker.steplink.crm.commons.model.SystemProperties;
import cc.linker.steplink.crm.commons.service.CommonsService;
import cc.linker.steplink.crm.merchant.dao.NewMallDao;
import cc.linker.steplink.crm.merchant.dao.ShopGoodsMapper;
import cc.linker.steplink.crm.merchant.dao.ShopGroupDao;
import cc.linker.steplink.crm.merchant.dao.mall.MallsMapper;
import cc.linker.steplink.crm.merchant.pojo.ShopGoods;
import cc.linker.steplink.crm.merchant.pojo.Sku;
import cc.linker.steplink.crm.merchant.service.acs.MerchantInfoService;
import cc.linker.steplink.crm.merchant.service.integral.IntegralGoodsService;
import cc.linker.steplink.crm.merchanth5.dao.MaiBaoLaDao;
import cc.linker.steplink.crm.merchanth5.service.MaiBaoLaService;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.merchanth5.service.acs.DynamicService;
import cc.linker.steplink.crm.merchanth5.service.redis.GoodsService;
import cc.linker.steplink.crm.response.GlobalException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mongodb.util.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@Slf4j
@Service
public class NewMallService {
    @Autowired
    private NewMallDao newMallDao;
    @Autowired
    private ShopGoodsMapper shopGoodsMapper;
    @Autowired
    private ShopGroupDao shopGroupDao;
    @Autowired
    private MaiBaoLaDao maiBaoLaDao;
    @Value("${casclient.clientHost}")
    private String clientHost;
    @Autowired
    private SystemProperties systemProperties;
    @Autowired
    private DynamicService dynamicService;
    @Autowired
    private MerchantInfoService merchantInfoService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MaiBaoLaService maiBaoLaService;
    @Autowired
    private MallsMapper mallsMapper;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private MallService mallService;
    @Autowired
    private IntegralGoodsService integralGoodsService;
    @Value("${system.scrm.scrmWebUrl}")
    private String scrmWebUrl;
    @Autowired
    private CommonsService commonsService;

    public Object getGoodsList(Map<String, Object> params) {
        int pageIndex = 1, pageSize = 20;
        Object pi = params.get("pageIndex");
        if (pi instanceof Integer && (int) pi >= 0) {
            pageIndex = (int) pi;
        }
        Object ps = params.get("pageSize");
        if (ps instanceof Integer && (int) ps >= 0) {
            pageSize = (int) ps;
        }
        String sort = "DESC";
        if(!StringUtils.isEmpty(params.get("sort"))){
            sort = params.get("sort").toString();
            if("ascending".equals(sort)){
                sort = "ASC";
            }else {
                sort = "DESC";
            }
        }
        params.put("sort",sort);
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> goodsList = newMallDao.getGoodsList(params);
        return new PageInfo<>(goodsList);
    }


    public void excelList(Map<String, Object> params, String orgId, HttpServletResponse response) {
        List<Map<String, Object>> goodsList = newMallDao.excelList(params);
        if(goodsList!=null && goodsList.size()>0){
            String token = newMallDao.getoken(orgId);
            for(Map<String, Object> goods:goodsList){
                try {
                    String goodsId =goods.get("goodsId").toString();
                    String endurl = clientHost + "/personal/login?token=" + token + "&m="
                            + URLEncoder.encode(scrmWebUrl + "/userCenter.html?goto=" + URLEncoder.encode("goodsDetail/" + goodsId+"?type=1", "utf-8"), "utf-8");
                    goods.put("endurl",endurl);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if(StringUtils.isEmpty(goods.get("memberAmount"))){
                    goods.put("memberJion","不参加");
                }else if("0.00".equals(goods.get("memberAmount").toString())){
                    goods.put("memberAmount","");
                    goods.put("memberJion","不参加");
                }else if(!"0.00".equals(goods.get("memberAmount").toString())){
                    goods.put("memberJion","参加");
                }
                if(!StringUtils.isEmpty(goods.get("mallsAmount")) && "0.00".equals(goods.get("mallsAmount").toString())){
                    goods.put("mallsAmount","");
                }
                if(!StringUtils.isEmpty(goods.get("mallsAmountMin")) && "0.00".equals(goods.get("mallsAmountMin").toString())){
                    goods.put("mallsAmountMin","");
                }
                if(!StringUtils.isEmpty(goods.get("mallsAmountMax")) && "0.00".equals(goods.get("mallsAmountMax").toString())){
                    goods.put("mallsAmountMax","");
                }
             }
        }
        this.exportList(goodsList,response);
    }

    public void exportList( List<Map<String, Object>> goodsList, HttpServletResponse response) {
        String[] title = {"商品id", "商品名称", "规格id", "商品规格", "商品类型","商品分组","价格（元）","会员价（元）","库存","累计销量","会员折扣","商品链接",
                "供货价（元）","最低建议售价（元）","最高建议售价（元）"};
        String fileName = "商品数据";
        String[] strings = {"goodsId", "goodsName", "skuId", "skuValue", "goodsType", "groupName", "moneyAmount", "memberAmount", "goodsCount", "salesNum", "memberJion", "endurl",
                "mallsAmount","mallsAmountMin","mallsAmountMax"};
        try {
            commonsService.excelDownload(goodsList, strings, title, fileName, response);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    public void changeGoodStatus(Map<String, Object> params, Integer mine) throws GlobalException {
        String goodsId = params.get("goodsId").toString();
        String orgId = params.get("orgId").toString();
        Integer payMode = maiBaoLaDao.getPayModeByOrgId(orgId);
        if (StringUtils.isEmpty(goodsId)) {
            throw GlobalException.build("商品id不能为空");
        }
        ShopGoods goods = shopGoodsMapper.getGoods(Long.valueOf(goodsId));
        if (mine == 0 || mine ==2) {
            String banned = goods.getBanned();
            if ("1".equals(banned)) {
                throw GlobalException.build("此商品被封禁");
            }
            //v1.9.2 判断 商家名称 联系我们 退货信息
            Map<String, Object> info = newMallDao.getMallInfo(params);
            if (info == null || info.get("storeName") == null || info.get("touchAddress") == null || info.get("returnMobilePhone") == null) {
                throw GlobalException.build("请先完成商家信息中的相关配置后上架商品！");
            }
            //  商家认证
            Map<String, Object> merInfo = newMallDao.getMerInfo(params);
            if (merInfo == null || !"2".equals(merInfo.get("checkStatus").toString())) {
                throw GlobalException.build("请先完成商家信息中的相关配置后上架商品。");
            }
            if(payMode != 3){
                // 支付配置
                Map<String, Object> payInfo = newMallDao.getPayInfo(params);
                if (payInfo == null) {
                    throw GlobalException.build("请先完成商家信息中的相关配置后，上架商品");
                }
            }

            // 公众号授权
            Map<String, Object> publicInfo = newMallDao.getPublicInfo(params);
            if (publicInfo == null || !"1".equals(publicInfo.get("state").toString())) {
                throw GlobalException.build("请先完成商家信息中的相关配置后上架商品");
            }
            newMallDao.changeGoodStatus(goodsId);

        } else if (mine == 1) {
            newMallDao.changeOrgStatus(goodsId);
        } else {
            throw GlobalException.build("商品类型不正确");
        }
        mallService.flushCartGoodsSkuInfo(Long.valueOf(goodsId));
    }

    public void save(Map<String, Object> params) throws GlobalException {
        Object goodsIdObj = params.get("goodsId");
        Object sku = params.get("sku");
        Long goodsId;
        // banner转json字符串
        Object goodsBanner = params.get("goodsBanner");
        String serialize = JSON.serialize(goodsBanner);
        params.put("goodsBanner", serialize);
        List groupId = (List) params.get("goodsGroup");
        int ifupdate = 0;
        // 是否供货商品
        boolean ifMalls = !StringUtils.isEmpty(params.get("malls")) && "1".equals(params.get("malls").toString());
        if (goodsIdObj != null && !"-1".equals(goodsIdObj.toString())) {
            ifupdate = 1;
            goodsId = Long.valueOf(goodsIdObj.toString());

            newMallDao.delSecKill(goodsId);
            if(!StringUtils.isEmpty(params.get("isSeckill")) && "1".equals(params.get("isSeckill").toString())){
                Map<String,Object> secKillParam = new HashMap<>();
                secKillParam.put("goodsId",goodsId);
                secKillParam.put("startTime",params.get("secKillStartTime"));
                secKillParam.put("endTime",params.get("secKillEndTime"));
                secKillParam.put("vipLimitStart",params.get("vipLimitStart"));
                secKillParam.put("vipLimitEnd",params.get("vipLimitEnd"));
                secKillParam.put("vipIds",params.get("vipIds"));
                secKillParam.put("seckillMultiole",params.get("seckillMultiole"));
                newMallDao.addSecKill(secKillParam);
            }
            ShopGoods goods = shopGoodsMapper.getGoods(goodsId);
            String banned = goods.getBanned();
            if ("1".equals(banned)) {
                throw GlobalException.build("此商品被封禁");
            }
            if (!(sku instanceof List) || ((List) sku).isEmpty()) {
                shopGoodsMapper.updateGoods(params);
            }
            // 删除商品规格关联关系
            shopGoodsMapper.deleteGoodsSpecs(goodsId);
            // 删除商品的sku
//            shopGoodsMapper.deleteSkus(goodsId);
            // 删除商品标签关系
            shopGoodsMapper.deleteGoodsLabels(goodsId);
            if (groupId != null && groupId.size() > 0) {
                // 更新商品分组
                Long[] longs = {goodsId};
                shopGroupDao.delRelationByGoodsIds(longs);
//                newMallDao.updateRelation(goodsId, groupId);
                newMallDao.updateRelationByList(goodsId, groupId);
            } else {
                // 删除商品分组
                Long[] longs = {goodsId};
                shopGroupDao.delRelationByGoodsIds(longs);
            }
            //删除产品服务关联关系
            newMallDao.delSerRelByGoodsId(goodsId);
        } else {
            Integer goodsCount = shopGoodsMapper.getGoodsCount(params);
            Integer goodsLimit = shopGoodsMapper.getGoodsLimitByOrgId(params);
            // 如果是供货商品不用判断上限
            if (!ifMalls) {
                if (goodsLimit == null) {
                    throw GlobalException.build("到达上限，无法创建");
                }
                if (goodsCount + 1 >= goodsLimit) {
                    throw GlobalException.build("到达上限，无法创建");
                }
            }
            if(StringUtils.isEmpty(params.get("isVirtual"))){
                params.put("isVirtual",0);
            }
            newMallDao.insertGoods(params);
            goodsId = Long.valueOf(params.get("goodsId").toString());

            if(!StringUtils.isEmpty(params.get("isSeckill")) && "1".equals(params.get("isSeckill").toString())){
                Map<String,Object> secKillParam = new HashMap<>();
                secKillParam.put("goodsId",goodsId);
                secKillParam.put("startTime",params.get("secKillStartTime"));
                secKillParam.put("endTime",params.get("secKillEndTime"));
                secKillParam.put("vipLimitStart",params.get("vipLimitStart"));
                secKillParam.put("vipLimitEnd",params.get("vipLimitEnd"));
                secKillParam.put("vipIds",params.get("vipIds"));
                secKillParam.put("seckillMultiole",params.get("seckillMultiole"));
                newMallDao.addSecKill(secKillParam);
            }

            // 如果是供货商品 新增时  其他未删除状态的供货商品排序字段加1
            if(ifMalls){
                newMallDao.updateMallsGoodsSort(goodsId);
            }
            Long[] longs = {goodsId};
            shopGroupDao.delRelationByGoodsIds(longs);
            if (groupId != null && groupId.size() > 0) {
                newMallDao.updateRelationByList(goodsId, groupId);
            }
            params.put("type", 1);
            params.put("desc", "新增"+params.get("goodsName"));
            dynamicService.recording(params);
        }
        mallService.flushGoodsCache(true,goodsId,null,0L);
        if (!StringUtils.isEmpty(params.get("categoryId")) && !StringUtils.isEmpty(params.get("attributeId"))) {
            saveGoodsCateAttr(goodsId, Integer.parseInt(params.get("categoryId").toString()), (String) params.get("attributeId"), null);
        }
        // 更新商品标签
        Object labels = params.get("labels");
        if (!StringUtils.isEmpty(labels)) {
            String[] split = labels.toString().split(",");
            if (split.length > 0) {
                shopGoodsMapper.updateGoodsLabels(goodsId, split);
            }
        }
        Object goodsSpec = params.get("goodsSpec");
        if (goodsSpec instanceof List && !((List) goodsSpec).isEmpty()) {
            for (Object o : (List) goodsSpec) {
                if (o instanceof Map) {
                    Map<String, Object> map = (Map) o;
                    map.put("goodsId", goodsId);
                    newMallDao.insertGoodsSpec(map);
                }
            }
        }
        if(!StringUtils.isEmpty(params.get("serviceIds"))){
            //添加关联关系
            String serviceIds = params.get("serviceIds").toString();
            List<String> servicelist= Arrays.asList(serviceIds.split(","));
            Map map = new HashMap();
            map.put("servicelist",servicelist);
            map.put("goodsId",goodsId);
            newMallDao.insertSerRel(map);
        }
        Long totalCount = 0L;
        List<Map<String,Object>> newSku = new ArrayList<>();
        if (sku instanceof List && !((List) sku).isEmpty()) {
            List<Long> skuIds = new ArrayList<>();
            Double mallsAmount = StringUtils.isEmpty(((List<Map>) sku).get(0).get("mallsAmount")) ? 0D : Double.parseDouble(((List<Map>) sku).get(0).get("mallsAmount").toString());
            for (Object o : (List) sku) {
                if (o instanceof Map) {
                    Map<String, Object> map = (Map) o;
                    map.put("goodsId", goodsId);
                    long newSkuId = 0L;
                    newMallDao.insertSku(map);
                    if(!StringUtils.isEmpty(map.get("skuId"))){
                        newSkuId = Long.parseLong(map.get("skuId").toString());
                        map.put("newSkuId",map.get("skuId"));
                    }else{
                        newSkuId = Long.parseLong(map.get("newSkuId").toString());
                    }
                    // 统计库存
                    long skuCount = Long.parseLong(map.get("goodsCount").toString());
                    mallService.flushGoodsCache(false,goodsId,String.valueOf(newSkuId),skuCount);
                    // 记录 存在的sku list 用于删除不存在的sku记录
                    skuIds.add(newSkuId);
                    // 往新的sku列表加 记录
                    newSku.add(map);
                    totalCount += skuCount;
                    // 取最小的供货价
                    double mixMallsAmount = StringUtils.isEmpty(map.get("mallsAmount")) ? 0D : Double.parseDouble(map.get("mallsAmount").toString());
                    if (mixMallsAmount < mallsAmount) {
                        mallsAmount = mixMallsAmount;
                    }
                }
            }
            // 删除未出现的skuId
            if(skuIds.size()>0 && !StringUtils.isEmpty(goodsId)){
                newMallDao.delSkuBySkuIds(skuIds,goodsId);
            }
            if (ifMalls) {
                // 供货商 商品 取最小值
                params.put("mallsAmount", mallsAmount);
            }
            params.put("goodsCount", totalCount);
            params.put("memberAmount", 0);
            shopGoodsMapper.updateGoods(params);
        }else{
            // 删除规格
            shopGoodsMapper.deleteSkus(goodsId);
        }

        if(totalCount<1 && !StringUtils.isEmpty(params.get("goodsCount"))){
            totalCount = Long.valueOf(params.get("goodsCount").toString());
        }
        mallService.flushGoodsCache(false,goodsId, null, totalCount);

        if (ifupdate == 1) {
            // 判断是否是失效状态 如果失效提示 提示商品被供货商下架，无法保存
            if(!ifMalls){
                Integer ifSave = shopGoodsMapper.checkGoodsStatusById(goodsId);
                if(ifSave>0){
                    throw GlobalException.build("此商品被供货商下架，无法保存");
                }
                // 更新供货商品信息 状态待配置 改为 未推广
                shopGoodsMapper.updateSalerGoodsStatus(goodsId);

                // change  (允许亏损，加亏损提示接口) 推广商品修改销售价 需要判断返润设置的比例 是否会造成亏损
                if(checkMallGoodsRewetting(goodsId, params, newSku)){
                    LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                    throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                }
            }
            // 3.供货商修改零售价或则供货价，提示“供货商修改商品信息或则有商品信息未填写，请调整”
            // 4.供货商调整商品规格导致商品规格在销售中存在差异，提示“供货商修改商品信息或则有商品信息未填写，请调整”
            if (ifMalls) {
                // 更新供货商品信息 状态待配置 改为 未推广
                shopGoodsMapper.updateMallsGoodsStatus(goodsId);
                // 更新关联的销售商商品数据
                updateMallGoodsToSalerGoods(goodsId, params, newSku);
            }else {
                //判断积分商品是否失效
                integralGoodsService.updateGoodsToIntegralGoods(goodsId, params, newSku,goodsSpec);
            }
        }
        redisTemplate.delete("idp_sourceImg_" + goodsId);
        redisTemplate.delete("goodsInfo:goods_info_" + goodsId);
    }

    /**
     * 判断用户修改后的价格是否会亏损
     */
    public void checkGoodsRewetting(Map<String, Object> params)
    {
        Long goodsId = Long.parseLong(params.get("goodsId").toString());

        // 判断是否推广商品
        Map<String,Object> goodsInfo = shopGoodsMapper.getGoodsInfo(goodsId);
        Object sku = params.get("sku");
        List<Map> newSku = (List<Map>) sku;
        // 判断返润比例金额是否大于佣金
        // 返润比例
        double promotionRebate = 0;
        String promotion = "0";
        if(goodsInfo!=null && !StringUtils.isEmpty(goodsInfo.get("promotion"))){
            promotion = goodsInfo.get("promotion").toString();
        }
        // 判断是否设置了返润比例 promotion
        if("1".equals(promotion)){
            promotionRebate = Double.parseDouble(goodsInfo.get("promotionRebate").toString());
        }
        double goodsFreight = 0;
        if(!StringUtils.isEmpty(params.get("freightTemplateId")) &&
                ((!StringUtils.isEmpty(params.get("isFreeFreight")) &&
                "0".equals(params.get("isFreeFreight").toString())) ||
                (!StringUtils.isEmpty(params.get("isFreight")) &&
                        "0".equals(params.get("isFreight").toString())))){
            goodsFreight = Double.valueOf(maiBaoLaDao.getLeastTemplateFee(params.get("freightTemplateId").toString()))*100;
        }else  if(!StringUtils.isEmpty(params.get("goodsFreight")) &&
                (((!StringUtils.isEmpty(params.get("isFreeFreight")) &&
                "0".equals(params.get("isFreeFreight").toString())) ||
                (!StringUtils.isEmpty(params.get("isFreight")) &&
                   "0".equals(params.get("isFreight").toString())))
                )

        ){
             goodsFreight = Double.parseDouble(params.get("goodsFreight").toString())*100;
        }
        if(goodsFreight>0){
            int goodsFreight2 = new BigDecimal(goodsFreight).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
            goodsFreight = goodsFreight2;
        }
        if(newSku==null || newSku.size()<1){
            // 单规格
            // 销售金额
            double amount = Double.parseDouble(params.get("moneyAmount").toString())*100;
            double reduceAmount = amount;
            if(!StringUtils.isEmpty(params.get("reduceAmount"))){
                reduceAmount=Double.parseDouble(params.get("reduceAmount").toString())*100;
            }
            // 供货价
            double mallsAmount = 0.0;
            if(!StringUtils.isEmpty(params.get("mallsAmount"))){
                mallsAmount = Double.parseDouble(params.get("mallsAmount").toString())*100;
            }
            // 返润金额
            double cost1 = amount*promotionRebate/100;
            cost1 = new BigDecimal(cost1).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
            // 佣金
            double cost2 = reduceAmount-mallsAmount;
            if(mallsAmount<=0){
                Double v1 = (reduceAmount+goodsFreight)*0.1;
                int allFee = new BigDecimal(v1).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                //自有商品要加运费-抽成
                cost2 += goodsFreight-allFee;
            }
            if(cost1>cost2 || cost2<0){
                LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
//                throw GlobalException.build("此商品成交后可能出现亏损，请修改");
            }
            // 会员价来判断是否亏损
            if(!StringUtils.isEmpty(params.get("memberAmount")) && !"0".equals(params.get("memberAmount").toString())){
                // 会员价
                double memberAmount = Double.parseDouble(params.get("memberAmount").toString())*100;
                double reduceMemberAmount = memberAmount;
                if(!StringUtils.isEmpty(params.get("reduceMemberAmount"))){
                    reduceMemberAmount = Double.parseDouble(params.get("reduceMemberAmount").toString())*100;
                }

                if(memberAmount>0){
                    // 会员价返润金额
                    double cost3 = memberAmount*promotionRebate/100;
                    cost3 = new BigDecimal(cost3).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    // 会员价返润佣金
                    double cost4 = reduceMemberAmount-mallsAmount;
                    if(mallsAmount<=0){
                        //自有商品要加运费-抽成
                        Double v1 = (reduceMemberAmount+goodsFreight)*0.1;
                        int allFee = new BigDecimal(v1).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                        cost4 += goodsFreight-allFee;
                    }
                    if(cost3>cost4  || cost4<0){
//                    throw GlobalException.build("此商品成交后可能出现亏损，请修改");
                        LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                        throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                    }
                }
            }
        }else{
            // 多规格
//            for(Map o1:newSku){
            for(int i=0;i<newSku.size();i++){
                Object o2 = newSku.get(i);
                Map o1 = BeanMapUtils.beanToMap(o2);
                if(o1.containsKey("empty")){
                    o1 = (Map<String,Object>)o2;
                }
                try {
//                    Sku o = BeanMapUtils.mapToBean(o1,Sku.class);
                    Map<String,Object> o = o1;
                    // 销售金额
                    double amount = 0;
                    if(!StringUtils.isEmpty(o.get("moneyAmount"))) {
                        amount = Double.valueOf(o.get("moneyAmount").toString()) * 100;
                    }
                    double reduceAmount = amount;
                    if(!StringUtils.isEmpty(o.get("reduceAmount"))){
                        reduceAmount = Double.valueOf(o.get("reduceAmount").toString())*100;
                    }
                    // 供货价
                    double mallsAmount =0.0;
                    if(!StringUtils.isEmpty(o.get("mallsAmount"))){
                        mallsAmount =  Double.valueOf(o.get("mallsAmount").toString())*100;
                    }
                    // 返润金额
                    double cost1 = amount*promotionRebate/100;
                    cost1 = new BigDecimal(cost1).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    // 佣金
                    double cost2 = reduceAmount-mallsAmount;
                    if(mallsAmount<=0){
                        //自有商品要加运费-抽成
                        Double v1 = (reduceAmount+goodsFreight)*0.1;
                        int allFee = new BigDecimal(v1).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                        cost2 += goodsFreight-allFee;
                    }
                    if(cost1>cost2 || cost2<0){
                        LOGGER.info("cost1-->"+cost1+"  cost2--->"+cost2);
                        LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                        throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
//                    throw GlobalException.build("此商品成交后可能出现亏损，请修改");
                    }
                    // 会员价来判断是否亏损
                    if(!StringUtils.isEmpty(o.get("memberAmount"))){
                        // 会员价
                        double memberAmount = Double.valueOf(o.get("memberAmount").toString())*100;
                        if(memberAmount>0){
                            double reduceMemberAmount = memberAmount;
                            if(!StringUtils.isEmpty(o.get("reduceMemberAmount"))){
                                reduceMemberAmount = Double.valueOf(o.get("reduceMemberAmount").toString())*100;
                            }

                            // 会员价返润金额
                            double cost3 = memberAmount*promotionRebate/100;
                            cost3 = new BigDecimal(cost3).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                            // 会员价返润佣金
                            double cost4 = reduceMemberAmount-mallsAmount;
                            if(mallsAmount<=0){
                                //自有商品要加运费-抽成
                                Double v1 = (reduceMemberAmount+goodsFreight)*0.1;
                                int allFee = new BigDecimal(v1).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                                cost4 += goodsFreight-allFee;
                            }
                            if(cost3>cost4 || cost4<0){
                                LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                                throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
//                        throw GlobalException.build("此商品成交后可能出现亏损，请修改");
                            }
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                    throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                }
            }
        }
    }

    /**
     * 根据机构用户获取小b
     *
     * @param userId
     * @return
     */
    public String getSalerId(String userId) {
        return newMallDao.getSalerId(userId);
    }

    public Object getGoodsListByUserId(Map<String, Object> params) {
        String adminId = (String) params.get("adminId");
        String customerId = merchantInfoService.getCustomerIdByAdminId(adminId);
        params.put("customerId", customerId);
        String sort = "DESC";
        if(!StringUtils.isEmpty(params.get("sort"))){
            sort = params.get("sort").toString();
            if("ascending".equals(sort)){
                sort = "ASC";
            }else {
                sort = "DESC";
            }
        }
        params.put("sort",sort);
        PageHelper.startPage(1, 99);
        List<Map<String, Object>> goodsList = newMallDao.getGoodsListByUserCode(params);
        return new PageInfo<>(goodsList);
    }

    public void savexb(Map<String, Object> params) throws GlobalException {
        if (params.containsKey("rebate")) {
            try {
                Integer rebate = (Integer) params.get("rebate");
            } catch (Exception e) {
                throw GlobalException.build("返利不正确");
            }
        } else {
            throw GlobalException.build("请填写返利");
        }
        List groupId = (List) params.get("goodsGroup");
        // 根据userId获取customerId
        String customerId = newMallDao.getCustomerIdByUserId(params);
        params.put("customerId", customerId);
        Object goodsBanner = params.get("goodsBanner");
        String serialize = JSON.serialize(goodsBanner);
        params.put("goodsBanner", serialize);
        int i = maiBaoLaDao.countCustomerId(customerId);
        Long goodsId;
        Integer quota = maiBaoLaDao.getQuotaByUserId(params.get("adminId").toString());
        int ifupdate = 0;
        boolean ifMalls = !StringUtils.isEmpty(params.get("malls")) && "1".equals(params.get("malls").toString());

        if ((!params.containsKey("goodsId") || !"-1".equals(params.get("goodsId").toString())) && i >= quota && quota != -1) {
            throw GlobalException.build("商品数量已经到达上限");
        } else if (params.containsKey("goodsId") && !StringUtils.isEmpty(params.get("goodsId")) && !"-1".equals(params.get("goodsId").toString())) {
            ifupdate = 1;
            goodsId = Long.valueOf(params.get("goodsId").toString());
            maiBaoLaDao.updateGoods(params);

            //秒杀参数
            newMallDao.delSecKill(goodsId);
            if(!StringUtils.isEmpty(params.get("isSeckill")) && "1".equals(params.get("isSeckill").toString())){
                Map<String,Object> secKillParam = new HashMap<>();
                secKillParam.put("goodsId",goodsId);
                secKillParam.put("startTime",params.get("secKillStartTime"));
                secKillParam.put("endTime",params.get("secKillEndTime"));
                secKillParam.put("vipLimitStart",params.get("vipLimitStart"));
                secKillParam.put("vipLimitEnd",params.get("vipLimitEnd"));
                secKillParam.put("vipIds",params.get("vipIds"));
                secKillParam.put("seckillMultiole",params.get("seckillMultiole"));
                newMallDao.addSecKill(secKillParam);
            }
            if (groupId != null && groupId.size() > 0) {
                // 更新商品分组
                Long[] longs = {goodsId};
                shopGroupDao.delRelationByGoodsIds(longs);
//                newMallDao.updateRelation(goodsId, groupId);
                newMallDao.updateRelationByList(goodsId, groupId);
            } else {
                // 删除商品分组
                Long[] longs = {goodsId};
                shopGroupDao.delRelationByGoodsIds(longs);
            }
            //删除产品服务关联关系
            newMallDao.delSerRelByGoodsId(goodsId);
        } else {
            Integer goodsCount = shopGoodsMapper.getGoodsCount(params);
            Integer goodsLimit = shopGoodsMapper.getGoodsLimitByOrgId(params);
            if (!ifMalls) {
                if (goodsLimit == null) {
                    throw GlobalException.build("到达上限，无法创建");
                }
                if (goodsCount + 1 >= goodsLimit) {
                    throw GlobalException.build("到达上限，无法创建");
                }
            }
            if(StringUtils.isEmpty(params.get("isVirtual"))){
                params.put("isVirtual",0);
            }
            maiBaoLaDao.insertGoods(params);
            // 更新销售员状态 有商品
            maiBaoLaDao.updateSaler(customerId);
            goodsId = Long.valueOf(params.get("goodsId").toString());

            //秒杀参数
            if(!StringUtils.isEmpty(params.get("isSeckill")) && "1".equals(params.get("isSeckill").toString())){
                Map<String,Object> secKillParam = new HashMap<>();
                secKillParam.put("goodsId",goodsId);
                secKillParam.put("startTime",params.get("secKillStartTime"));
                secKillParam.put("endTime",params.get("secKillEndTime"));
                secKillParam.put("vipLimitStart",params.get("vipLimitStart"));
                secKillParam.put("vipLimitEnd",params.get("vipLimitEnd"));
                secKillParam.put("vipIds",params.get("vipIds"));
                newMallDao.addSecKill(secKillParam);
            }

            if(ifMalls){
                newMallDao.updateMallsGoodsSort(goodsId);
            }

            if (groupId != null && groupId.size() > 0) {
                newMallDao.updateRelationByList(goodsId, groupId);
            }
        }
        mallService.flushGoodsCache(true,goodsId,null,0L);
        if (!StringUtils.isEmpty(params.get("categoryId")) && !StringUtils.isEmpty(params.get("attributeId"))) {
            saveGoodsCateAttr(goodsId, Integer.parseInt(params.get("categoryId").toString()), (String) params.get("attributeId"), customerId);
        }
        // 删除商品规格关联关系
        shopGoodsMapper.deleteGoodsSpecs(goodsId);
        // 删除商品的sku
//        shopGoodsMapper.deleteSkus(goodsId);
        // 更新商品标签
        Object labels = params.get("labels");
        if (!StringUtils.isEmpty(labels)) {
            String[] split = labels.toString().split(",");
            if (split.length > 0) {
                shopGoodsMapper.updateGoodsLabels(goodsId, split);
            }
        }
        if(!StringUtils.isEmpty(params.get("serviceIds"))){
            //添加关联关系
            String serviceIds = params.get("serviceIds").toString();
            List<String> servicelist= Arrays.asList(serviceIds.split(","));
            Map map = new HashMap();
            map.put("servicelist",servicelist);
            map.put("goodsId",goodsId);
            newMallDao.insertSerRel(map);
        }
//        Long totalCount = 0L;
        Object sku = params.get("sku");
        Object goodsSpec = params.get("goodsSpec");
        if (goodsSpec instanceof List && !((List) goodsSpec).isEmpty()) {
            for (Object o : (List) goodsSpec) {
                if (o instanceof Map) {
                    Map<String, Object> map = (Map) o;
                    map.put("goodsId", goodsId);
                    newMallDao.insertGoodsSpec(map);
                }
            }
        }
        Long totalCount = 0L;
        List<Map<String,Object>> newSku = new ArrayList<>();
        if (sku instanceof List && !((List) sku).isEmpty()) {
            List<Long> skuIds = new ArrayList<>();
            Double mallsAmount = StringUtils.isEmpty(((List<Map>) sku).get(0).get("mallsAmount")) ? 0D : Double.parseDouble(((List<Map>) sku).get(0).get("mallsAmount").toString());
            for (Object o : (List) sku) {
                if (o instanceof Map) {
                    Map<String, Object> map = (Map) o;
                    map.put("goodsId", goodsId);
                    long newSkuId = 0L;
                    newMallDao.insertSku(map);
                    if(!StringUtils.isEmpty(map.get("skuId"))){
                        newSkuId = Long.parseLong(map.get("skuId").toString());
                        map.put("newSkuId",map.get("skuId"));
                    }else{
                        newSkuId = Long.parseLong(map.get("newSkuId").toString());
                    }
                    // 记录 存在的sku list 用于删除不存在的sku记录
                    skuIds.add(newSkuId);
                    // 往新的sku列表加 记录
                    newSku.add(map);
                    // 统计库存
                    long skuCount = Long.parseLong(map.get("goodsCount").toString());
                    totalCount += skuCount;
//                    newMallDao.insertSku(map);
                    mallService.flushGoodsCache(false,goodsId,String.valueOf(newSkuId),skuCount);
                    // 取最小的供货价
                    double mixMallsAmount = StringUtils.isEmpty(map.get("mallsAmount")) ? 0D : Double.parseDouble(map.get("mallsAmount").toString());
                    if (mixMallsAmount < mallsAmount) {
                        mallsAmount = mixMallsAmount;
                    }
                }
            }
            // 删除未出现的skuId
            if(skuIds.size()>0 && !StringUtils.isEmpty(goodsId)){
                newMallDao.delSkuBySkuIds(skuIds,goodsId);
            }
            if (ifMalls) {
                // 供货商 商品 取最小值
                params.put("mallsAmount", mallsAmount);
            }
            params.put("goodsCount", totalCount);
            params.put("memberAmount", 0);
            shopGoodsMapper.updateGoods(params);
        }else{
            // 删除规格
            shopGoodsMapper.deleteSkus(goodsId);
        }

        if(totalCount<1 && !StringUtils.isEmpty(params.get("goodsCount"))){
            totalCount = Long.valueOf(params.get("goodsCount").toString());
        }
        mallService.flushGoodsCache(false,goodsId, null, totalCount);
        if (ifupdate == 1) {
            // 判断是否是失效状态 如果失效提示 提示商品被供货商下架，无法保存
            if(!ifMalls){
                Integer ifSave = shopGoodsMapper.checkGoodsStatusById(goodsId);
                if(ifSave>0){
                    throw GlobalException.build("此商品被供货商下架，无法保存");
                }
                // 更新供货商品信息 状态待配置 改为 未推广
                shopGoodsMapper.updateSalerGoodsStatus(goodsId);
                // 推广商品修改供货价 需要判断返润设置的比例 是否会造成亏损
                if(checkMallGoodsRewetting(goodsId, params, newSku)){
                    LOGGER.error("调整后可能会有商品出现亏损，goodsId:"+goodsId);
                    throw GlobalException.build("调整后可能会有商品出现亏损，请调整。");
                }
            }
            // 3.供货商修改零售价或则供货价，提示“供货商修改商品信息或则有商品信息未填写，请调整”
            // 4.供货商调整商品规格导致商品规格在销售中存在差异，提示“供货商修改商品信息或则有商品信息未填写，请调整”
            if (ifMalls) {
                // 更新供货商品信息 状态待配置 改为 未推广
                shopGoodsMapper.updateMallsGoodsStatus(goodsId);
                // 更新关联的销售商商品数据
                updateMallGoodsToSalerGoods(goodsId, params, newSku);
            }else {
                //判断积分商品是否失效
                integralGoodsService.updateGoodsToIntegralGoods(goodsId, params, newSku,goodsSpec);
            }
        }
        redisTemplate.delete("idp_sourceImg_" + goodsId);
        redisTemplate.delete("goodsInfo:goods_info_" + goodsId);
    }

    private boolean checkMallGoodsRewetting(Long goodsId, Map<String, Object> params, List<Map<String, Object>> newSku) {
        if(goodsId==null){
            goodsId=-1L;
        }
        // 判断是否推广商品
        Map<String,Object> goodsInfo = shopGoodsMapper.getGoodsInfo(goodsId);
        if(goodsInfo==null || StringUtils.isEmpty(goodsInfo.get("mallsGoodsId"))){
            return false;
        }
        // 判断是否设置了返润比例 promotion
        if("1".equals(goodsInfo.get("promotion"))){
            // 判断返润比例金额是否大于佣金
            // 返润比例
            double promotionRebate = Double.parseDouble(goodsInfo.get("promotionRebate").toString());
            if(newSku==null || newSku.size()<1){
                // 单规格
                // 销售金额
                double amount = Double.parseDouble(params.get("moneyAmount").toString())*100;
                // 供货价
                double mallsAmount = Double.parseDouble(goodsInfo.get("mallsAmount").toString());
                // 返润金额
                double cost1 = amount*promotionRebate/100;
                int cost1fee = new BigDecimal(cost1*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                cost1 = cost1fee/100.00;
                // 佣金
                double cost2 = amount-mallsAmount;
                if(cost1>cost2 || cost2<0){
                    return true;
                }
                // 会员价来判断是否亏损
                if(!"0".equals(params.get("memberAmount").toString())){
                    // 会员价
                    double memberAmount = Double.parseDouble(params.get("memberAmount").toString())*100;
                    if(memberAmount>0){
                        // 会员价返润金额
                        double cost3 = memberAmount*promotionRebate/100;
                        cost3 = new BigDecimal(cost3).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                        // 会员价返润佣金
                        double cost4 = memberAmount-mallsAmount;
                        if(cost3>cost4 || cost4<0){
                            return true;
                        }
                    }
                }
            }else{
                // 多规格
                for(Map<String,Object> o:newSku){
                    // 销售金额
                    double amount = Double.parseDouble(o.get("moneyAmount").toString())*100;
                    // 供货价
                    double mallsAmount = Double.parseDouble(o.get("mallsAmount").toString())*100;
                    // 返润金额
                    double cost1 = amount*promotionRebate/100;
                    int cost1fee = new BigDecimal(cost1*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                    cost1 = cost1fee/100.00;
                    // 佣金
                    double cost2 = amount-mallsAmount;
                    if(cost1>cost2 || cost2<0){
                        return true;
                    }
                    /* 会员价来判断是否亏损 */
                    if(!StringUtils.isEmpty(o.get("memberAmount")) && !"0".equals(o.get("memberAmount"))){
                        // 会员价
                        double memberAmount = Double.parseDouble(o.get("memberAmount").toString())*100;
                        if(memberAmount>0){
                            // 会员价返润金额
                            double cost3 = memberAmount*promotionRebate/100;
                            cost3 = new BigDecimal(cost3).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                            // 会员价返润佣金
                            double cost4 = memberAmount-mallsAmount;
                            if(cost3>cost4 || cost4<0){
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

    /**
     * 处理供货商修改商品  销售商商品同步和失效等问题
     *
     * @param goodsId
     * @param params
     */
    private void updateMallGoodsToSalerGoods(Long goodsId, Map<String, Object> params, List<Map<String,Object>> newSku) {
        List<Long> goodsIds = new ArrayList<>();
        // 3.供货商修改零售价或则供货价，提示“供货商修改商品信息或则有商品信息未填写，请调整”
        // 4.供货商调整商品规格导致商品规格在销售中存在差异，提示“供货商修改商品信息或则有商品信息未填写，请调整”

        //获取销售商商品集合
        List<Map<String, Object>> salerGoodsList = mallsMapper.getSalerGoodsList(goodsId);
        // 销售价小于新的供货价
        Double supplierMallsAmount = (Double.parseDouble(params.get("mallsAmount").toString()));
        // 销售价不在新的零售区间
        Double supplierMallsAmountMin = 0.0;
        if(!StringUtils.isEmpty(params.get("mallsAmountMin"))){
            supplierMallsAmountMin = (Double.parseDouble(params.get("mallsAmountMin").toString()));
        }
        Double supplierMallsAmountMax = 0.0;
        if(!StringUtils.isEmpty(params.get("mallsAmountMax"))){
            supplierMallsAmountMax = (Double.parseDouble(params.get("mallsAmountMax").toString()));
        }

        // 获取商品spec
        List<Map<String,Object>> goodsSpec = mallsMapper.getSpecById(goodsId);

        if (salerGoodsList.size() > 0) {
            for (Map<String, Object> salerGoods : salerGoodsList) {
                // 销售商商品
                Long salerGoodsId = (Long) salerGoods.get("goodsId");
                // 删除库存缓存
                mallService.flushGoodsCache(true,salerGoodsId,null,null);
                // 判断 销售商当前的商品规格
                List<Map<String, Object>> salerGoodsSku = mallsMapper.getSkuById(salerGoodsId);
                // 判断 规格是否修改
                if (newSku != null && !newSku.isEmpty()) {
                    // 删除商品规格关联关系
                    shopGoodsMapper.deleteGoodsSpecs(salerGoodsId);
                    for (Map<String, Object> o : goodsSpec) {
                        if (o != null) {
                            o.put("goodsId", salerGoodsId);
                            o.remove("id");
                            newMallDao.insertGoodsSpec(o);
                        }
                    }
                    // 赋值一个新的list<map>
                    List<Map<String, Object>> sku = copyList(newSku);
                    // 供货商多规格 销售商单规格
                    if (salerGoodsSku.size() < 1) {
                        goodsIds.add(salerGoodsId);
                        // 删除商品的sku
                        shopGoodsMapper.deleteSkus(salerGoodsId);
                        for (Map<String, Object> o : sku) {
                            if (o != null) {
                                o.put("goodsId", salerGoodsId);
                                o.put("moneyAmount", o.get("mallsAmountMin"));
                                o.put("mallsAmount", o.get("mallsAmount"));
                                o.put("mallsSkuId", o.get("newSkuId"));
                                o.remove("skuId");
                                newMallDao.insertSku(o);
                                mallService.flushGoodsCache(false,salerGoodsId, o.get("newSkuId").toString(),
                                        Long.valueOf(o.get("goodsCount").toString()));
                            }
                        }
                    } else {
                        boolean ifLose = false;
                        // 都是多规格 比较规格和价格
                        List<Long> salerSkuIds = new ArrayList<>();
                        for (Map<String, Object> map :  sku) {
                            if (map != null) {
                                // 有新规格则失效
                                if(StringUtils.isEmpty(map.get("skuId"))){
                                    ifLose = true;
                                }
                                // 供货商skuId 赋值为 销售商的mallsSkuId
                                Long mallsSkuId = Long.parseLong(map.get("newSkuId").toString());
                                Map<String, Object> skuInfo = mallsMapper.getSkuInfoByMallsSkuIdAndGoodsId(mallsSkuId, salerGoodsId);
                                if (skuInfo == null || skuInfo.size() < 1) {
                                    // 当前sku 为新sku  插入
                                    map.remove("skuId");
                                    map.put("moneyAmount",map.get("mallsAmountMin"));
                                }else {
                                    // 当前sku 为老sku  更新
                                    map.put("skuId",skuInfo.get("skuId"));
                                    map.put("moneyAmount",skuInfo.get("moneyAmount"));
                                    map.put("originalPrice",skuInfo.get("originalPrice"));
                                    map.put("memberAmount",skuInfo.get("memberAmount"));
                                    map.put("originalCost",skuInfo.get("originalCost"));
                                    map.put("productCode",skuInfo.get("productCode"));
                                    map.put("productId",skuInfo.get("productId"));
                                    // 判断价格是否失效
                                    if(!ifLose){
                                        supplierMallsAmountMin = (Double.parseDouble(map.get("mallsAmountMin").toString()));
                                        supplierMallsAmountMax = (Double.parseDouble(map.get("mallsAmountMax").toString()));
                                        // 当前sku供货价
                                        double skuSupplierMallsAmount = Double.parseDouble(map.get("mallsAmount").toString());
                                        // 当前sku销售价
                                        double skuMoneyAmount = Double.parseDouble(skuInfo.get("moneyAmount").toString());
                                        // 销售价小于当前供货价 小于最小零售价 大于最大零售价
                                        if (skuMoneyAmount < skuSupplierMallsAmount || skuMoneyAmount < supplierMallsAmountMin || skuMoneyAmount > supplierMallsAmountMax) {
                                            ifLose = true;
                                        }
                                        // 判断返润 佣金
                                        if(!StringUtils.isEmpty(salerGoods.get("promotion"))){
                                            // 有设置返润
                                            double promotionRebate = Double.parseDouble(salerGoods.get("promotionRebate").toString());
                                            // 佣金
                                            double cost1 = skuMoneyAmount-skuSupplierMallsAmount;
                                            // 返润金额
                                            double cost2 = skuMoneyAmount*promotionRebate/100;
                                            int cost2fee = new BigDecimal(cost2*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                                            cost2 = cost2fee/100.00;
                                            if(cost1<cost2){
                                                ifLose = true;
                                            }
                                        }
                                    }
                                }
                                map.put("goodsId", salerGoodsId);
                                map.put("mallsSkuId", mallsSkuId);
                                map.remove("newSkuId");
                                newMallDao.insertSku(map);
                                long salerSkuId = 0L;
                                if(!StringUtils.isEmpty(map.get("skuId"))){
                                    salerSkuId = Long.parseLong(map.get("skuId").toString());
                                }else{
                                    salerSkuId = Long.parseLong(map.get("newSkuId").toString());
                                }
                                salerSkuIds.add(salerSkuId);
                                mallService.flushGoodsCache(false,salerGoodsId, String.valueOf(salerSkuId),
                                        Long.valueOf(map.get("goodsCount").toString()));
                            }
                        }
                        // 删除不存在的sku
                        if(salerSkuIds.size()>0 && !StringUtils.isEmpty(goodsId)){
                            newMallDao.delSkuBySkuIds(salerSkuIds,salerGoodsId);
                        }
                        if (ifLose) {
                            goodsIds.add(salerGoodsId);
                        }
                    }
                } else {
                    // 供货商单规格 销售商多规格
                    if (salerGoodsSku.size() > 0) {
                        goodsIds.add(salerGoodsId);
                        // 删除销售商商品规格关联关系
                        shopGoodsMapper.deleteGoodsSpecs(salerGoodsId);
                        // 删除销售商商品的sku
                        shopGoodsMapper.deleteSkus(salerGoodsId);
                    } else {
                        // 供货商单规格 销售商单规格
                        // 销售价
                        double moneyAmount = Double.parseDouble(salerGoods.get("moneyAmount").toString());
                        // 都是单规格  比较价格
                        if (moneyAmount < supplierMallsAmount || moneyAmount < supplierMallsAmountMin || moneyAmount > supplierMallsAmountMax) {
                            // 失效
                            goodsIds.add(salerGoodsId);
                        }else{
                            // 判断返润 佣金
                            if(!StringUtils.isEmpty(salerGoods.get("promotion"))){
                                // 有设置返润
                                double promotionRebate = Double.parseDouble(salerGoods.get("promotionRebate").toString());
                                // 佣金
                                double cost1 = moneyAmount-supplierMallsAmount;
                                // 返润金额
                                double cost2 = moneyAmount*promotionRebate/100;
                                int cost2fee = new BigDecimal(cost2*100).setScale(0, BigDecimal.ROUND_HALF_EVEN).intValue();
                                cost2 = cost2fee/100.00;
                                if(cost1<cost2){
                                    goodsIds.add(salerGoodsId);
                                }
                            }
                        }
                    }
                }
                // 同步供货商商品数据到销售商商品 更新库存 供货价 建议零售价 物流信息
                Map<String, Object> temp = new HashMap<>();
                temp.put("goodsId", salerGoodsId);
                temp.put("goodsCount", params.get("goodsCount"));
                temp.put("mallsAmount", supplierMallsAmount);
                temp.put("mallsAmountMin", supplierMallsAmountMin);
                temp.put("mallsAmountMax", supplierMallsAmountMax);
                temp.put("freightTemplateId", params.get("freightTemplateId"));
                temp.put("goodsFreight", params.get("goodsFreight"));
                temp.put("isFreight", params.get("isFreight"));
                mallsMapper.updateSalerGoods(temp);
                mallService.flushGoodsCache(false,salerGoodsId, null, Long.valueOf(params.get("goodsCount").toString()));
            }
        }
        if (goodsIds.size() > 0) {
            String mallsInvalid = "供货商修改商品信息或则有商品信息未填写，请调整";
            mallsMapper.changeGoodsStatusByGoodsId(goodsIds, mallsInvalid,3);
        }
    }

    public List<Map<String, Object>> copyList(List<Map<String, Object>> a){
        List<Map<String, Object>> b = new ArrayList();
        if(a!=null && a.size()>0){
            for (int i=0;i<a.size();i++){
                HashMap<String, Object> c=  new HashMap<>();
                c.putAll(a.get(i));
                b.add(c);
            }
        }
        return  b;
    }

    /**
     * 刷新商品缓存
     * @param goodsId 商品Id
     * @param skuId 规格Id
     * @param goodsCount 库存数量
     */

    public void updateStatus(Map<String, Object> params) throws GlobalException {
        Integer mine = (Integer) params.get("mine");
        String customerId = newMallDao.getCustomerIdByUserId(params);
        params.put("customerId", customerId);
        String goodsId = params.get("goodsId").toString();
        if (mine == 0 || mine == 2) {
            ShopGoods goods = shopGoodsMapper.getGoods(Long.valueOf(goodsId));
            String banned = goods.getBanned();
            if ("1".equals(banned)) {
                throw GlobalException.build("此商品被封禁");
            }
            Map<String, Integer> map = newMallDao.ifCanUpGoods(params);
            if (map == null) {
                throw GlobalException.build("用户信息获取失败");
            }
            if (map.get("authenticateState") != 1) {
                throw GlobalException.build("未通过审核暂不能发布商品");
            }
            //v1.9.2 判断 商家名称 联系我们 退货信息
            Map<String, Object> info = newMallDao.getMallInfo(params);
            if (info == null || info.get("storeName") == null || info.get("touchAddress") == null || info.get("returnMobilePhone") == null) {
                throw GlobalException.build("请先完成商家信息中的相关配置后上架商品");
            }
            if (map.get("goodsStatus") == 0) {
                throw GlobalException.build("您的商铺已暂停使用，请联系商家");
            }

            if (!params.containsKey("goodsId")) {
                throw GlobalException.build("商品id不正确");
            }
            newMallDao.changeGoodStatus(goodsId);
            maiBaoLaDao.cleanGoodsBindArticle(goodsId);
        } else if (mine == 1) {
            newMallDao.changeOrgStatus(goodsId);
        } else {
            throw GlobalException.build("商品类型不正确");
        }
        mallService.flushCartGoodsSkuInfo(Long.valueOf(goodsId));
    }

    public void judgeStateOfAdmin(Map<String, Object> params) throws GlobalException {
        String customerId = newMallDao.getCustomerIdByUserId(params);
        params.put("customerId", customerId);
        Map<String, Integer> map = newMallDao.ifCanUpGoods(params);
        if (map == null) {
            throw GlobalException.build("用户信息获取失败");
        }

//        if (map.get("authenticateState") != 1) {
//            throw GlobalException.build("未通过审核暂不能发布商品");
//        }
        // 获取是否设置商家信息
//        Map<String, Object> info = newMallDao.getMallInfo(params);
//        if (info == null || StringUtils.isEmpty(info.get("storeName"))) {
//            throw GlobalException.build("商家名称未填写不能发布商品");
//        }
        // 获取机构是否设置支付商户号
//        String payId = newMallDao.getPayIdByOrgId(params);
//        if (StringUtils.isEmpty(payId)) {
//            throw GlobalException.build("暂未设置支付商户号");
//        }


        Integer goodsCount = newMallDao.getGoodsCountByCustomerId(customerId);
        Integer quota = maiBaoLaDao.getQuotaByUserId(params.get("adminId").toString());
        if (goodsCount >= quota && quota != -1) {
            throw GlobalException.build("商品数量已达上限");
        }
    }

    public Object listPaging(Map<String, Object> params) throws GlobalException, UnsupportedEncodingException {
        String userId = (String) params.get("userId");
        if (StringUtils.isEmpty(userId)) {
            throw GlobalException.build("缺少用户信息");
        }
        if (!params.containsKey("orgId")) {
            throw GlobalException.build("机构id不能为空");
        }
        params.put("adminId", userId);
        String customerId = newMallDao.getCustomerIdByUserId(params);
        if (!StringUtils.isEmpty(customerId)) {
            params.put("saler", customerId);
        } else {
            params.put("saler", "");
        }
        Integer pageIndex = (Integer) params.get("pageIndex");
        if (pageIndex == null) {
            pageIndex = 1;
        }
        Integer pageSize = (Integer) params.get("pageSize");
        if (pageSize == null) {
            pageSize = 20;
        }
        Object orgId = params.get("orgId");
//        Integer payMode = mallService.getPayModeByOrgId(params);
        String scrmWebUrl = systemProperties.getAcsScrmWebUrl();
        String token = newMallDao.getTokenByOrgId(orgId);
        if (StringUtils.isEmpty(token)) {
            throw GlobalException.build("找不到对应机构");
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<Map<String, Object>> list = newMallDao.listPaging(params);
        for (Map<String, Object> map : list) {
            String goodsId = map.get("goodsId").toString();
            String belongId = (String) map.get("belongId");
            String promotion = (String) map.get("promotion");
            Integer goodsType = (Integer) map.get("goodsType");
            String pagePath = this.getPagePathByGoodsType(goodsType);
            boolean flag = false;
            if (StringUtils.isEmpty(belongId) && "0".equals(promotion)) {
                flag = true;
            }
            String url = clientHost + "/personal/login?token=" + token + "&m=";
            String encode = URLEncoder.encode(pagePath + goodsId + "?type=" + (flag ? "0" : "1"), "UTF-8");
            String encode1 = URLEncoder.encode(scrmWebUrl + "userCenter.html?goto=" + encode, "UTF-8");
            url += encode1;

            map.put("url", url);
        }
        return new PageInfo<>(list);
    }

    /**
     * 通过商品类型获取页面路径
     */
    private String getPagePathByGoodsType(Integer goodsType) {
        String pagePath;
        switch (goodsType) {
            case 3:
                // 内容
                pagePath = "mediaDetail/";
                break;
            case 4:
                // 专栏
                pagePath = "columnDetail/";
                break;
            case 5:
                // 报名
                pagePath = "activityForm/";
                break;
            case 6:
                // 会员卡
                pagePath = "memberDetail/";
                break;
            case 7:
                pagePath = "form-system/";
                break;
            default:
                // 商品
                pagePath = "goodsDetail/";
                break;
        }
        return pagePath;
    }


    public void judgeStateOfAdminOrg(Map<String, Object> params) {
        Integer state = newMallDao.judgeStateOfAdminOrg(params);
        if (state == 0) {
            throw GlobalException.build("暂未通过审核");
        }
        String shopName = newMallDao.getShopNameByOrgId(params);
        if (StringUtils.isEmpty(shopName)) {
            throw GlobalException.build("暂未设置商家名称");
        }
//        String payId = newMallDao.getPayIdByOrgId(params);
//        if (StringUtils.isEmpty(payId)) {
//            throw GlobalException.build("暂未设置支付商户号");
//        }
    }

    public void saveGoodsCateAttr(Long goodsId, Integer categoryId, String attributeId, String customerId) {
        String attrBaseId = attributeId;//newMallDao.getGoodBaseAttr(attributeId);
        //用于计算AI辅助的数据
        Map<String, Object> missMactch = new HashMap<>();
        missMactch.put("goodMemId", goodsId);
        missMactch.put("matchType", 1);
        //廓形-大小
        String[] one = {"47", "48", "49"};
        List<String> attrs = Arrays.asList(attrBaseId.split(","));
        for (String indexOne : one) {
            if (attrs.contains(indexOne)) {
                missMactch.put("indexOne", indexOne);
                break;
            }
        }
        //颜色-纯度
        String[] two = {"34", "35", "36"};
        for (String indexTwo : two) {
            if (attrs.contains(indexTwo)) {
                missMactch.put("indexTwo", indexTwo);
                break;
            }
        }
        //颜色-明度
        String[] three = {"30", "31", "32"};
        for (String indexThree : three) {
            if (attrs.contains(indexThree)) {
                missMactch.put("indexThree", indexThree);
                break;
            }
        }
        //廓形-直曲
        String[] four = {"43", "44", "45"};
        for (String indexFour : four) {
            if (attrs.contains(indexFour)) {
                missMactch.put("indexFour", indexFour);
                break;
            }
        }
        missMactch.put("belongId", customerId);
        //存储用户计算AI辅助的数据
        Integer ifInMatch = newMallDao.ifInMatch(missMactch);
        if (ifInMatch == 0) {
            newMallDao.addMatch(missMactch);
        } else {
            newMallDao.updateMatch(missMactch);
        }
        newMallDao.addGoodsCateAttr(goodsId, categoryId, attributeId);
    }

    public Boolean checkMerInfo(Map params) {
        String orgId = params.get("orgId").toString();
        Integer payMode = maiBaoLaDao.getPayModeByOrgId(orgId);
        if ((Boolean) params.get("ifSales")) {
            String customerId = newMallDao.getCustomerIdByUserId(params);
            params.put("customerId", customerId);
            // 判断saler表的authenticateState
            Integer authenticateState = newMallDao.getAuthenticateStateByCid(customerId);
            if (authenticateState != 1) {
                return false;
            }
        }
        //v1.9.2 判断 商家名称 联系我们 退货信息
        Map info = newMallDao.getMallInfo(params);
        if (info == null || info.get("storeName") == null || info.get("touchAddress") == null || info.get("returnMobilePhone") == null) {
            return false;
        }
        //  商家认证
        Map merInfo = newMallDao.getMerInfo(params);
        if (merInfo == null || !"2".equals(merInfo.get("checkStatus").toString())) {
            return false;
        }
        if(payMode!=3){
        // 支付配置
        Map payInfo = newMallDao.getPayInfo(params);
        if (payInfo == null) {
            return false;
        }
        }

        // 公众号授权
        Map publicInfo = newMallDao.getPublicInfo(params);
        if (publicInfo == null || !"1".equals(publicInfo.get("state").toString())) {
            return false;
        }
        return true;
    }


    /**
     * 公共商品新增编辑
     *
     * @param goodsContent 商品简介
     * @param goodsCover   商品封面
     * @param goodsGroup   商品分组
     * @param goodsId      商品id,编辑时传
     * @param goodsName    商品名
     * @param goodsStatus  商品状态
     * @param moneyAmount  价格
     * @param purchaseType 购买方式 1 纯积分； 2 纯金额； 3 积分+金额
     * @param goodsType    商品类型 1 自有商品，2 推广商品，3 知识付费(内容)， 4 知识付费（专栏）
     * @param orgId        机构
     * @param adminId      用户
     */
    public void savePublic(Map<String, Object> params) throws GlobalException {
        params.put("goodsFreight", 0);
        Object goodsIdObj = params.get("goodsId");
        Long goodsId;
        List groupId = (List) params.get("goodsGroup");
        Object customerId = params.get("customerId");
        if (customerId == null) {
            params.put("customerId", "");
        }
        if (goodsIdObj != null) {
            goodsId = Long.valueOf(goodsIdObj.toString());
            shopGoodsMapper.updateGoods(params);
            // 删除商品标签关系
            shopGoodsMapper.deleteGoodsLabels(goodsId);
            if (groupId != null && groupId.size() > 0) {
                // 更新商品分组
                Long[] longs = {goodsId};
                shopGroupDao.delRelationByGoodsIds(longs);
                newMallDao.updateRelationByList(goodsId, groupId);
            } else {
                // 删除商品分组
                Long[] longs = {goodsId};
                shopGroupDao.delRelationByGoodsIds(longs);
            }
        } else {
            newMallDao.insertGoodsPublic(params);
            goodsId = Long.valueOf(params.get("goodsId").toString());
            if (groupId != null && groupId.size() > 0) {
                newMallDao.updateRelationByList(goodsId, groupId);
            }
            params.put("type", 1);
            params.put("desc", "新增"+params.get("goodsName"));
            dynamicService.recording(params);
        }
        // 更新商品标签
        Object labels = params.get("labels");
        if (!StringUtils.isEmpty(labels)) {
            String[] split = labels.toString().split(",");
            if (split.length > 0) {
                shopGoodsMapper.updateGoodsLabels(goodsId, split);
            }
        }
        mallService.flushCartGoodsSkuInfo(goodsId);
    }

    public void judgeGoodsLimitByOrgId(Map<String, Object> params) {
        Integer goodsCount = shopGoodsMapper.getGoodsCount(params);
        Integer goodsLimit = shopGoodsMapper.getGoodsLimitByOrgId(params);
        if (goodsLimit == null) {
            throw GlobalException.build("到达上限，无法创建");
        }
        if (goodsCount + 1 >= goodsLimit) {
            throw GlobalException.build("到达上限，无法创建");
        }
    }

    public String qrCode(String goodsId, Integer goodsType, boolean flag,String token) {
        try {
            String pagePath = this.getPagePathByGoodsType(goodsType);
            String s;
            if(goodsType == 6){
                //会员卡
                s = pagePath + "?memberId=" + goodsId;
            }else if(goodsType == 7) {
                s = pagePath + "?formId=" + goodsId;
            }
            else if (goodsType == 5) {
                s = pagePath + "?enrollId=" + goodsId;
            } else {
                s = pagePath + goodsId + "?type=" + (flag ? "1" : "0");
            }
            if (StringUtils.isEmpty(token)) {
                throw GlobalException.build("无效二维码");
            }

            String url = clientHost + "/personal/login?token=" + token + "&m=";
            String encode = URLEncoder.encode(s, "UTF-8");
            String encode1 = URLEncoder.encode(systemProperties.getAcsScrmWebUrl() + "userCenter.html?goto=" + encode, "UTF-8");

            url += encode1;
            return "redirect:" + url;
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("qrCode===error", e);
            throw GlobalException.fail();
        }
    }

    public void updateSort(Map<String, Object> params) {
        newMallDao.updateSort(params);
    }
}
